
import {
  dynastyList,poetryTypeList
} from "../../../utils/commondata.js";

import {
  request
} from "../../../utils/request.js";
import regeneratorRuntime from '../../../utils/runtime';
var appInst =  getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    mainColor:appInst.globalData.mainColor,
    chapterList:[],
    page:1,
    dynastyIndex:-1,
    dynastyList:dynastyList(),
    dynasty:'',//dynastyList()[0].name,
    typeIndex:7,
    typeList:poetryTypeList(),
    typeName:poetryTypeList()[7].name,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let pages = getCurrentPages();
    let currentPage = pages[pages.length - 1];
    let options = currentPage.options;
    const { type} = options;
    if(type){
      this.setData({
        typeName:type,
        typeIndex:-1,
      })
    }
    let {dynasty,typeName}  = this.data;
    this.loadChapter(1,dynasty,typeName);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let {dynasty,typeName}  = this.data;
    this.setData({
      chapterList:[],
    })
    this.loadChapter(1,dynasty,typeName);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let {page,dynasty,typeName}  = this.data;
    page = page + 1;
    this.loadChapter(page,dynasty,typeName);
  },

  /**
   * 朝代变化
   * @param {*} e 
   */
  handleDynastySelect(e){
    const {index} = e.currentTarget.dataset;
    this.setData({
      dynastyIndex:index,
      typeIndex:-1,
      chapterList:[],
    });
    this.loadChapter(1,this.data.dynastyList[index].name,'');
  },
  /**
   * 类型选择
   * @param {*} e 
   */
  handleTypeSelect(e){
    const {index} = e.currentTarget.dataset;
    this.setData({
      dynastyIndex:-1,
      typeIndex:index,
      chapterList:[],
    });
    this.loadChapter(1,'',this.data.typeList[index].name);
  },
  /**
   * 
   * 点击古诗
   * @param {*} e 
   */
  handlePoetClick(e){
    let {id} = e.currentTarget.dataset;
    wx.navigateTo({
      url:'/pages/chapter/detail/index?chapterId=' + id,
    });
  },
  /**
   * 
   * 加载古诗词
   * @param {*} page 页码 
   * @param {*} dynasty 朝代
   * @param {*} typeName 类型
   */
  async loadChapter(page,dynasty,typeName){
    const res = await request({
      url: "/chapter/pageQuery?page=" + page + "&dynasty=" + dynasty + "&typeName=" + typeName,
      method: "get"
    });
    if(res.code != 0){
      return;
    }
    this.setData({
      page:page,
      dynasty:dynasty,
      typeName:typeName,
      chapterList:[...this.data.chapterList,...res.data.list],
    });
  },



})